package pkg

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

type MysqlConfig struct {
	Host     string `yaml:"host" mapstructure:"host"`
	Port     int    `yaml:"port" mapstructure:"port"`
	UserName string `yaml:"username" mapstructure:"username"`
	Password string `yaml:"password" mapstructure:"password"`
	DBname   string `yaml:"dbname" mapstructure:"dbname"`
	Env      string `yaml:"env" mapstructure:"env"` // 环境变量
}

func createDB(username string, password string, host string, port int, database string) (*gorm.DB, error) {
	//dsn := "gjf:123456@tcp(121.4.213.43:3306)/gjf?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True", // &loc=Local 数据库不处理时区
		username,
		password,
		host,
		port,
		database,
	)
	// 配置日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	_db, err := gorm.Open(
		mysql.Open(dsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // 禁用创建表名复数带 s
				//TablePrefix:   "",   // 统一表前缀, 自定义表名会覆盖全局 goods_
			},
			//DisableForeignKeyConstraintWhenMigrating: true, // AutoMigrate 会自动创建数据库外键约束，您可以在初始化时禁用此功能
			Logger: newLogger,
		})
	if err != nil {
		return nil, err
	}
	return _db, err
}

func MysqlInit(mysqlConfig MysqlConfig) (*gorm.DB, error) {
	db, err := createDB(mysqlConfig.UserName, mysqlConfig.Password, mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.DBname)
	if err != nil {
		return nil, err
	}
	if mysqlConfig.Env == "dev" {
		db = db.Debug()
	}
	return db, nil
}
